<template>
  <div class="page-container">
    <section class="flex offset-fotm-item">
      <div>
        <el-form @submit.prevent="search" :inline="true">
          <el-form-item label="查询">
            <el-input v-model="searchForm.keyword"
                      placeholder="宿舍号"/>
          </el-form-item>
          <el-form-item label="楼栋号">
            <el-select placeholder="全部" size="medium" style="width:100px;" v-model="searchForm.building_num">
              <el-option :key="item._id"
                         :label="item.text"
                         :value="item.building_num"
                         v-for="item in options.buildings"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button native-type="submit" size="medium" type="primary">查询</el-button>
            <el-button @click="showAddDormDialog" size="medium" type="primary">新增宿舍</el-button>
          </el-form-item>
        </el-form>
      </div>
    </section>
    <!-- 宿舍表格 -->
    <el-table :data="DormData"
              :default-sort="{prop: 'building_num', order: 'ascending'}"
              v-loading="loading"
              border
              stripe
              :header-cell-style="{backgroundColor:'aliceblue',color:'#666'}">
      <el-table-column align="center" label="宿舍号" prop="DORM_ID" sortable/>
      <el-table-column align="center" label="楼栋号" prop="DORM_BUILDID" sortable/>
      <el-table-column align="center" label="已住人数" prop="reside_count" sortable/>
      <el-table-column align="center" label="容纳人数" prop="contain_count" sortable/>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-tooltip content="查看/编辑信息">
            <el-button @click="editDetail(scope.row)" circle plain size="mini">
              <el-icon><EditPen /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除">
            <el-button @click="deleteDorm(scope.row)"
                       circle
                       plain
                       size="mini"
                       type="danger">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="DormData?.length || 0"
      @current-change="handlePageChange"
      style="margin-top: 20px;"
    ></el-pagination>
    <!-- 添加宿舍 -->
    <add-dorm v-model="isShowAddDorm" @showAddDormEvent="handleShowAddDormEvent" @update="getData"/>
    <!-- 修改宿舍信息 -->
    <edit-dorm v-model="isShowEditDorm" :curDorm="curDorm" @showEditDormEvent="handleShowEditDormEvent" @update="getData"/>
  </div>
</template>

<script>
  import AddDorm from "@/components/dorm/add-dorm";
  import {getAllBuildings} from "@/api/building";
  import { RemoveDorm,ShowDorm } from '@/api/index/admin';
  import EditDorm from "@/components/dorm/edit-dorm";
  import _ from "lodash"
  import { ElMessage, ElMessageBox } from 'element-plus';

  export default {
    name: "dorm-manage",
    components: {EditDorm, AddDorm},
    data() {
      return {
        paging:{
          current:1,
        },
        loading: true,
        searchForm: {
          keyword: "",
          building_num: 0
        },
        startIndex: 0,
        endIndex: 10, // 每页显示数量
        currentPage: 1, // 当前页码
        pageSize: 10, // 每页显示数量
        DormData: [
{ DORM_ID: 'A101', DORM_BUILDID: '1号楼', reside_count: 3, contain_count: 6 },
{ DORM_ID: 'A102', DORM_BUILDID: '1号楼', reside_count: 4, contain_count: 6 },
      ],
        selectedDorms: [],
        isShowAddDorm: false,
        options: {
          buildings: []
        },
        isShowEditDorm: false,
        curDorm: {}
      }
    },
    methods: {
      handlePageChange(newPage) {
        this.currentPage = newPage;
        this.startIndex = (newPage - 1) * this.pageSize;
        this.endIndex = this.startIndex + this.pageSize;
      },
      search() {
        this.paging.current = 1;
        this.getData();
      },
      getData() {
        this.loading = true;
        ShowDorm().then(res=>{
        this.DormData = res.data.data;
        this.loading = false;
      })
    },
      curPageChange(page) {
        this.paging.current = page;
        this.getData();
      },
      showAddDormDialog() {
        this.isShowAddDorm = true;
      },
      editDetail(row) {
        this.curDorm = _.cloneDeep(row);
        this.isShowEditDorm = true;
      },
      deleteDorm(row) {
        ElMessageBox.confirm(
          '此操作将永久删除该宿舍且无法恢复，是否继续？',
          '通过申请',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(
          RemoveDorm({id:row.id})
          .then(rep=>{
            let code=rep.data.code
            if(code===200){
              this.$message({
                type: 'success',
                message: '删除成功',
              })
              this.getData();
            }else {
              ElMessage({
                type: 'error',
                message: '删除失败',
              })
            }
              })
        ).catch(()=>{
          ElMessage({
            type: 'error',
            message: '已取消',
          })
        }
        )
      },
      handleShowEditDormEvent(){
        this.isShowEditDorm = false;
      },
      handleShowAddDormEvent(){
        this.isShowAddDorm = false;
      }
    },
    async mounted() {
      this.getData()
      try {
        const res = await getAllBuildings();
        if (res && res.data && res.data.data) {
          this.options.buildings = res.data.data;
          this.options.buildings.forEach(item => item.text = item.building_num + '号楼');
        } else {
          console.error('获取楼栋信息失败');
        }
      } catch (error) {
        console.error('获取楼栋信息失败', error);
      }
    }
  }
</script>